class Solution(object):
    def findLatestStep(self, arr, m):
        n = len(arr)
        if m == n:
            return n
        ans = [0] * n
        p = [i for i in range(n)]
        rank = [1] * n
        self.c = 0
        self.index = -1

        def find(x):
            if x == p[x]:
                return x
            else:
                p[x] = find(p[x])
                return p[x]

        def union(x, y):
            rootx = find(x)
            rooty = find(y)
            if rank[rootx] == m:
                self.c -= 1
            if rank[rooty] == m:
                self.c -= 1
            if rootx < rooty:
                p[rooty] = rootx
                rank[rootx] += rank[rooty]
                if rank[rootx] == m:
                    self.c += 1
            else:
                p[rootx] = rooty
                rank[rooty] += rank[rootx]
                if rank[rooty] == m:
                    self.c += 1

        for i in range(n):
            node = arr[i] - 1
            ans[node] = 1
            count = 0
            if node > 0:
                if ans[node - 1]:
                    union(node, node - 1)
            if node < n - 1:
                if ans[node + 1]:
                    union(node, node + 1)
            if m == 1:
                self.c += 1
            if self.c > 0:
                self.index = i + 1
        return self.index


data = Solution()
arr = [3, 5, 1, 2, 4]
m = 1
print(data.findLatestStep(arr, m))
